package com.bytz.modules.cms.pay.config;

import com.bytz.common.exception.BytzBootException;
import com.chinapay.secss.SecssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * ChinaPay 配置
 * @author shanxuezhong
 */
@Slf4j
@Profile("!test")
public class ChinaPayConfig {

    @Value("${bytz.pay.china-pay.security-properties}")
    private String propertyFile;

    @Bean
    public SecssUtil secssUtil() {
        SecssUtil secssUtil = new SecssUtil();
        Resource resource = new ClassPathResource(propertyFile);
        Properties properties;
        try {
            properties = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            throw new BytzBootException("加载chinapay-security.properties出错：", e);
        }

        boolean bool = secssUtil.init(properties);
        if (bool) {
            log.info("ChinaPay交易证书、验签证书初始化成功！");
        } else {
            throw new BytzBootException("ChinaPay交易证书、验签证书初始化失败：" + secssUtil.getErrCode() + "=" + secssUtil.getErrMsg());
        }

        return secssUtil;
    }
}
